<template>
  <div class="container">
    <p style="height: 18px;line-height: 16px;" class="title">顺序编排学校</p>
    <step index="1"></step>
    <div class="table-wrapper">
      <el-table :data="manuallyData" border class="c-table" style="width: 100%" v-loading="loading">
        <el-table-column label="考试日期" width="220">
          <template slot-scope="scope">
            <p>{{`${scope.row.date}  ${scope.row.time}`}}</p>
            <p>{{`座位剩余：${scope.row.seat}个`}}</p>
          </template>
        </el-table-column>
        <el-table-column label="待编排学校">
          <template slot-scope="scope">
            <div class="clearfix">
              <div class="school-item" :class="{'checked': sch.checked, 'cross': sch.cross}" v-for="(sch, idx) in scope.row.schoolData" :key="idx" @click="checkedSchool(scope.$index, idx, sch, sch.checked)">
                <p class="school">{{sch.schoolName}}</p>
                <div class="info">
                  <p>考生数：{{sch.stuNum}}人</p>
                  <p>已分配：{{sch.allocateNum}}人</p>
                </div>
                <el-tooltip class="item" content="同一个学校不能跨两天考试。请重新编排。" placement="top" v-if="sch.cross">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
                <i class="el-icon-circle-check" v-else></i>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="btn">
      <a href="javascript:;" class="save" @click="saveManuallyOrder()">下一步</a>
      <a href="javascript:;" class="cancel" @click="$router.push({ name: 'sequenceSchoolStep1' })">上一步</a>
    </div>
  </div>
</template>

<script>
import * as util from '@/common/util.js'
import step from '@/components/step.vue'
export default {
  components: {
    step
  },
  data () {
    return {
      loading: false,
      manuallyData: [],
      manuallyInfo: null,
      schoolList: []
    }
  },
  mounted () {
    this.initManuallyData()
  },
  methods: {
    // 初始化排序数据
    initManuallyData () {
      this.loading = true
      let _manuallyInfo = null
      this.manuallyInfo = _manuallyInfo = JSON.parse(sessionStorage.getItem('manually'))
      let _manuallyData = []
      _manuallyInfo.schoolData = _manuallyInfo.schoolData.map(item => {
        let _item = item
        _item.checked = false
        _item.allocateNum = 0
        return _item
      })
      _manuallyInfo.schoolData.unshift({
        stuNum: _manuallyInfo.stuNum,
        schoolName: _manuallyInfo.pointName,
        id: _manuallyInfo.id,
        distance: 0,
        checked: false,
        allocateNum: 0
      })
      this.schoolList = JSON.parse(JSON.stringify(_manuallyInfo.schoolData))
      for (let i = 0; i < _manuallyInfo.examDays; i++) {
        _manuallyData.push({
          schoolData: JSON.parse(JSON.stringify(_manuallyInfo.schoolData)),
          seat: _manuallyInfo.mSeat,
          // seat: _manuallyInfo.mSeat,
          totalSeat: _manuallyInfo.mSeat,
          // totalSeat: _manuallyInfo.mSeat,
          date: util.formatDate(new Date(_manuallyInfo.beginDate).getTime() + i * 86400000, 'yyyy/MM/dd'),
          time: '上午'
        })
        _manuallyData.push({
          schoolData: JSON.parse(JSON.stringify(_manuallyInfo.schoolData)),
          seat: _manuallyInfo.fSeat,
          totalSeat: _manuallyInfo.fSeat,
          date: util.formatDate(new Date(_manuallyInfo.beginDate).getTime() + i * 86400000, 'yyyy/MM/dd'),
          time: '下午'
        })
      }
      this.manuallyData = _manuallyData
      this.loading = false
    },
    // 选择学校
    checkedSchool (pidx, idx, school, val, type = null) {
      let that = this
      if (school.stuNum === 0) {
        this.$message.error('该校没有可以分配的考生')
        return false
      }
      let _schoolItem = this.manuallyData[pidx]
      let _schoolItemNearby = this.manuallyData[pidx % 2 === 0 ? pidx + 1 : pidx - 1]
      if (!val) {
        // 该校已经分配完成，无需再分配
        if (school.stuNum === _schoolItemNearby.schoolData[idx].allocateNum) {
          this.$message.error('该校已经分配完成，无需再分配')
          return false
        }
        // 当天剩余座位不足
        if (_schoolItem.seat === 0) {
          that.$message.error('该时间段座位已经满，请选择其他时间段')
          return false
        }

        if (_schoolItem.seat + _schoolItemNearby.seat < school.stuNum - _schoolItemNearby.schoolData[idx].allocateNum && type !== 2) {
          that.$message.error('当天剩余座位不足')
          return false
        }
      }
      _schoolItem.schoolData[idx].checked = !val
      // 判断跨天
      this.checkedManuallyData(pidx, idx, school, val)
      if (!val) {
        if (_schoolItem.seat > school.stuNum && _schoolItemNearby.seat === _schoolItemNearby.totalSeat) {
          _schoolItem.schoolData[idx].allocateNum = school.stuNum
          _schoolItem.seat = _schoolItem.seat - school.stuNum
        } else {
          if (_schoolItemNearby.seat !== _schoolItemNearby.totalSeat) {
            if (_schoolItemNearby.schoolData[idx].allocateNum === 0 && _schoolItem.seat > school.stuNum) {
              _schoolItem.schoolData[idx].allocateNum = school.stuNum
              _schoolItem.seat = _schoolItem.seat - school.stuNum
            } else if (_schoolItem.seat - (_schoolItemNearby.schoolData[idx].stuNum - _schoolItemNearby.schoolData[idx].allocateNum) >= 0) {
              _schoolItem.schoolData[idx].allocateNum = _schoolItemNearby.schoolData[idx].stuNum - _schoolItemNearby.schoolData[idx].allocateNum
              _schoolItem.seat = _schoolItem.seat - _schoolItem.schoolData[idx].allocateNum
            } else {
              _schoolItem.schoolData[idx].allocateNum = _schoolItem.seat
              _schoolItem.seat = 0
              this.checkedSchool(pidx % 2 === 0 ? pidx + 1 : pidx - 1, idx, school, val, 2)
            }
          } else if (school.checked) {
            if (_schoolItem.seat - school.stuNum < 0) {
              _schoolItem.schoolData[idx].allocateNum = _schoolItem.seat
              _schoolItem.seat = 0
              this.checkedSchool(pidx % 2 === 0 ? pidx + 1 : pidx - 1, idx, school, val, 2)
            } else {
              _schoolItem.schoolData[idx].allocateNum = _schoolItem.schoolData[idx].stuNum - school.allocateNum
              _schoolItem.seat = _schoolItem.seat - _schoolItem.schoolData[idx].allocateNum
            }
          }
        }
      } else {
        _schoolItem.seat += _schoolItem.schoolData[idx].allocateNum
        _schoolItem.schoolData[idx].allocateNum = 0
      }
      this.$set(this.manuallyData, pidx, _schoolItem)
      this.schoolList[idx].allocateNum = _schoolItem.schoolData[idx].allocateNum
    },
    // 检查不能跨天
    checkedManuallyData (pidx, idx, school, val) {
      let that = this
      let _manuallyList = []
      for (let i = 0; i < this.manuallyData.length; i = i + 2) {
        let _am = this.manuallyData[i].schoolData[idx].checked ? 1 : 0
        let _pm = this.manuallyData[i + 1].schoolData[idx].checked ? 1 : 0
        _manuallyList.push(_am + _pm)
      }
      let _num = 0
      let _crossDay = false
      _manuallyList.map((item, idx) => {
        _num += item
      })
      if (_manuallyList[0] === 1 && _manuallyList[1] === 1) {
        _crossDay = true
      }
      let _schoolItem = this.manuallyData[pidx]
      if (val) {
        _schoolItem.schoolData[idx].cross = false
        that.schoolList.cross = false
        return false
      }
      if (_num > 2 || _crossDay) {
        _schoolItem.schoolData[idx].cross = true
        that.schoolList.cross = true
      } else {
        _schoolItem.schoolData[idx].cross = false
        that.schoolList.cross = false
      }
    },
    // 保存编排数据
    saveManuallyOrder () {
      let that = this
      let schoolIds = []
      let manuallyData = {
        pointId: that.manuallyInfo.id,
        // pointOrder: 1
      }
      let _isCross = false
      that.schoolList.map(item => {
        if (item && item.cross) {
          _isCross = true
        }
      })
      if (_isCross) {
        that.$message.error('同一个学校不能跨两天考试。请重新编排。')
        return false
      }
      that.manuallyData.map((item, idx) => {
        item.schoolData.map((sch, sidx) => {
          if (sch.checked) {
            if (schoolIds.indexOf(sch.id) === -1) {
              schoolIds.push(sch.id)
            }
            if (manuallyData.hasOwnProperty(`id${sch.id}`)) {
              manuallyData[`id${sch.id}`].partDay2 = 1
              manuallyData[`id${sch.id}`].num2 = sch.allocateNum
            } else {
              manuallyData[`id${sch.id}`] = {
                day: parseInt(idx / 2),
                partDay1: item.time === '上午' ? 0 : 1,
                num1: sch.allocateNum
              }
            }
          }
        })
      })
      manuallyData.schoolIds = schoolIds.join(',')
      // 学校未分配完成检查
      let isComplete = true
      let colLine = that.manuallyData[0].schoolData.length
      let rowLine = that.manuallyData.length
      let _schoolNames = []
      for (let i = 0; i < colLine; i++) {
        let _allocateNum = 0
        for (let j = 0; j < rowLine; j++) {
          _allocateNum += that.manuallyData[j].schoolData[i].allocateNum
        }
        if (_allocateNum !== that.manuallyData[0].schoolData[i].stuNum) {
          isComplete = false
          _schoolNames.push(that.manuallyData[0].schoolData[i].schoolName)
        }
      }
      if (!isComplete) {
        that.$message.error(_schoolNames.join(',') + '学校人数未分配完成')
        return false
      }
      // 保存編排信息
      that.$http.manuallyGenerateTable(manuallyData).then(res => {
        if (res.data && res.data.length) {
          sessionStorage.setItem('manuallyStep2', JSON.stringify(res))
          sessionStorage.setItem('manuallyStep2Data', JSON.stringify(manuallyData))
          this.$router.push({ name: 'sequenceSchoolStep3' })
        } else {
          that.$message.error(res.msg)
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
color = #4177ff
background = #f3f3f3
@import url('../../assets/styles/base.css');
.school-item
  width 166px
  height 112px
  border 1px solid #ccc
  border-radius 5px
  margin-top 10px
  margin-bottom 10px
  position relative
  margin-right 20px
  float left
  cursor pointer
  text-align left
  &:hover
    border-color #3F82FF
  &.checked
    border-color #3F82FF
    i
      display block
  &.cross
    border-color #FE6E6E
    i
      color #FE6E6E
  .school
    padding-left 17px
    margin-top 12px
    text-align: left;
    font-size: 16px;
    color: #000;
    width: 140px;
    line-height: 20px;
  .info
    position absolute
    bottom 10px
    p
      padding-left 20px
      line-height 20px
      font-size 12px
      color #999999
  i
    position absolute
    right 15px
    bottom 12px
    color color
    font-size 20px
    display none
  &.active
    border 1px solid color
.btn
  margin-top 30px
  a
    display inline-block
    width 70px
    height 38px
    text-align center
    line-height 38px
    border-radius 5px
    color #fff
    text-decoration none
    margin-right 14px
    &.save
      background color
    &.cancel
      color color
      border 1px solid color
</style>
